package net.akkz.beanFactory;

import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import net.akkz.dbFactory.DbManage;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;


public class BeanFactory
{
	private Map<String, Object> beans;

	public void init()
	{
		beans = new HashMap<String, Object>();
		
		try
		{
			InputStream is = this.getClass().getClassLoader().getResourceAsStream("beans.xml");
			SAXReader reader = new SAXReader();
			Document doc = reader.read(is);
			Element root = doc.getRootElement();
			
			//------初始化类------
			Iterator<Element> i = root.elementIterator("bean");
			while (i.hasNext())
			{
				Element bean = (Element) i.next();
				String id = bean.attributeValue("id");
				String clazz = bean.attributeValue("class");
				
				this.beans.put(id, Class.forName(clazz).newInstance());
			}
			
			//------注入参数------
			i = root.elementIterator("bean");
			while (i.hasNext())
			{
				Element bean = (Element) i.next();
				String id = bean.attributeValue("id");
				
				Iterator p = bean.elementIterator("property");
				while(p.hasNext())
				{
					Element property = (Element)p.next();
					
					String name = property.attributeValue("name");
					String iocBean = property.attributeValue("ref");
					
					String method = "set" + name.substring(0, 1).toUpperCase() + name.substring(1);

					Object tBean = this.beans.get(id);
					Object tIocBean = this.beans.get(iocBean);
					
					tBean.getClass().getMethod(method, tBean.getClass().getDeclaredField(name).getType()).invoke(tBean, tIocBean);
				}
			}
			
			//------初始化数据库参数------
			Element database = (Element)root.element("database");
			if(database != null)
			{
				String ref = database.attributeValue("ref");
				String username = database.elementTextTrim("username");
				String password = database.elementTextTrim("password");
				String url = database.elementTextTrim("url");
	
				DbManage dbBean = (DbManage)this.beans.get(ref);
				
				dbBean.setUsername(username);
				dbBean.setPassword(password);
				dbBean.setUrl(url);
			}
		}
		catch (InstantiationException | IllegalAccessException | ClassNotFoundException e)
		{
			e.printStackTrace();
		}
		catch (IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException | NoSuchFieldException e)
		{
			e.printStackTrace();
		}
		catch (DocumentException e)
		{
			e.printStackTrace();
		}
		catch (NullPointerException e)
		{
			e.printStackTrace();
		}
	}
	

	@SuppressWarnings("unchecked")
	public <T> T getBean(String name)
	{
		return (T) beans.get(name);
	}
}
